<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="belongCategory">
        <el-select v-model="queryParams.belongCategory" clearable placeholder="请选择分类">
          <el-option
            v-for="item in productCategoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAddCategory"
        >管理分类</el-button>

        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAddProduct"
        >新增产品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="productInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编码" align="center" prop="id" />
<!--      <el-table-column label="产品编码" align="center" prop="coding" />-->
      <el-table-column label="产品名称" align="center" prop="name" />
      <el-table-column label="规格" align="center" prop="specification" />
      <el-table-column label="所属分类" align="center" prop="belongCategoryName" />
      <el-table-column label="单价（元）" align="center" prop="price" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      @current-change="changePage($event)"
      layout="prev, pager, next"
      :total="total">
    </el-pagination>

    <!-- 添加或修改产品分类对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-tag
          v-if="title == '添加产品分类'"
          :key="tag"
          v-for="tag in dynamicTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="title == '添加产品分类' && inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-if="!inputVisible && title == '添加产品分类'" class="button-new-tag" size="small" @click="showInput">+ 添加产品分类</el-button>
        <el-form-item v-if="title == '添加产品信息' || title == '修改产品信息'" label="选择分类" prop="belongCategory">
          <el-select v-model="form.belongCategory" placeholder="请选择分类">
            <el-option
              v-for="item in productCategoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="title == '添加产品信息' || title == '修改产品信息'" label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item v-if="title == '添加产品信息' || title == '修改产品信息'" label="产品规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入产品规格" />
        </el-form-item>
        <el-form-item v-if="title == '添加产品信息' || title == '修改产品信息'" label="产品单位" prop="unit">
          <el-select
            v-model="form.unit"
            filterable
            allow-create
            default-first-option
            placeholder="请选择产品单位">
            <el-option
              v-for="item in unitList"
              :key="item.label"
              :label="item.label"
              :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="title == '添加产品信息' || title == '修改产品信息'" label="单价(元)" prop="price">
          <el-input v-model="form.price" placeholder="请输入产品单价" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, exportProduct } from "@/api/jxc/productInfo.js";
import { listCategory, getCategory, delCategory, addCategory, updateCategory, exportCategory } from "@/api/jxc/productCategory.js";

export default {
  name: "Category",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 产品详情列表
      productInfoList: [],
      //产品分类列表
      productCategoryList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
      },
      goodsList:[],
      // 表单参数
      form: {},
      //分类表单
      categoryForm:{},
      // 表单校验
      rules: {
      },
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      //单位列表
      unitList:[{label:'台'},{label:'个'},{label:'条'},{label:'双'},{label:'只'},
        {label:'米'},{label:'块'},{label:'卷'},{label:'支'},{label:'笔'},{label:'辆'},{label:'把'}]
    };
  },
  created() {
    this.getList();
    this.getCategoryList()
  },
  methods: {
    //分页
    changePage(e){
      this.queryParams.pageNum = e
      this.getList()
    },
    /** 获取产品分类列表 */
    getCategoryList(){
      listCategory().then(res=>{
        this.productCategoryList = res.data
        res.data.forEach(item=>{
          this.dynamicTags.push(item.name)
        })
      })
    },
    handleClose(tag) {
      let id = ''
      this.productCategoryList.forEach(item =>{
        if (item.name == tag) id = item.id
      })
      delCategory(id).then(res=>{
        this.dynamicTags = []
        this.getCategoryList()
      })
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        // this.dynamicTags.push(inputValue);
        let obj = {}
        obj.name = inputValue
        addCategory(obj).then(res=>{
          this.dynamicTags = []
          this.getCategoryList()
        })
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    /** 查询产品分类列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        // console.log(response.data,'----')
        this.productInfoList = response.data
        this.total = response.total ;
        this.loading = false;
        this.goodsList = []
        // console.log(this.categoryList);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAddCategory() {
      this.reset();
      this.open = true;
      this.title = "添加产品分类";
    },
    handleAddProduct() {
      this.reset();
      this.open = true;
      this.title = "添加产品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.info;
        this.open = true;
        this.title = "修改产品信息";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            this.productCategoryList.forEach(item=>{
              if (item.id == this.form.belongCategory) {
                this.form.belongCategoryName = item.name
              }
            })
            updateProduct(this.form).then(response => {
              if (response.code === 0) {
                this.$message("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$message(response.msg);
              }
            });
          } else {
            //获取分类名字
            this.productCategoryList.forEach(item=>{
              if (item.id == this.form.belongCategory) this.form.belongCategoryName = item.name
            })
            if (this.form.unit !== undefined&& this.form.unit.trim().length > 2) {
              this.$message.warning("产品单位最多只允许输入2个字符")
              return
            }
            if (isNaN(this.form.price)) {
              this.$message.warning("单价只允许输入数字")
              return
            }
            this.productInfoList.forEach(item=>{
              if (this.form.name === item.name) {
                this.productInfoList.forEach(product=>{
                  if (this.form.specification === product.specification) {
                    this.$message.warning("该产品已存在该型号，请重新添加")
                    return
                  }
                })
              }
            })
            addProduct(this.form).then(response => {
              if (response.code === 0) {
                this.open = false;
                this.productInfoList = []
                this.getList();
              } else {
                this.$message(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;

      this.$confirm('是否确认删除产品分类id为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
        if (typeof ids != "number") {
          let str = ''
          ids.forEach(item=>{
            str += item + ','
            return delProduct(str);
          })
        }else {
          return delProduct(ids);
        }
        }).then(() => {
          this.getList();
          this.$message("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有产品分类数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportProduct(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.el-pagination {
  text-align: center;
  margin-top: 30px;
}
</style>
